package com.yzx.lifeassistants.model.impl;

import java.util.List;
import java.util.Properties;

import org.json.JSONException;
import org.json.XML;

import android.content.Context;

import com.yzx.lifeassistants.bean.Lecture;
import com.yzx.lifeassistants.model.IQueryLecture;
import com.yzx.lifeassistants.model.analysis.QueryLectureAnalysis;
import com.yzx.lifeassistants.model.callback.IQueryLectureCB;
import com.yzx.lifeassistants.utils.HttpClientUtil;
import com.yzx.lifeassistants.utils.IHttpCallBack;
import com.yzx.lifeassistants.utils.LogcatUtils;
import com.yzx.lifeassistants.utils.PropertyUtil;

/**
 * @Description: 查询讲座信息
 * @author: yzx
 * @time: 2016-3-17 下午8:57:18
 */
public class QueryLectureImpl implements IQueryLecture {
	public static final String TAG = "QueryLectureImpl";
	private String url;// URL
	private IQueryLectureCB queryCallBack;// 回调

	public QueryLectureImpl(Context context, IQueryLectureCB queryCallBack) {
		this.queryCallBack = queryCallBack;
		Properties properties = PropertyUtil.getProperties(context,
				"base.properties");
		url = properties.getProperty("query_lecture_url");
	}

	/**
	 * @Description: 查询讲座信息
	 */
	@Override
	public void queryLecture(int page, String catalogPath) {
		String url = this.url + "?page=" + page + "&catalogPath=-30480-30555-";
		HttpClientUtil.sendRequest(url, null, new IHttpCallBack() {

			@Override
			public void onFinish(String response) {
				try {
					LogcatUtils.i(XML.toJSONObject(response).toString());
					if (QueryLectureAnalysis.isNull(response)) {// 返回结果为空
						LogcatUtils.e(TAG, "查询讲座结果为空");
						queryCallBack.queryError(IQueryLectureCB.RESULR_NULL);
					} else {// 返回结果不为空
						LogcatUtils.i(TAG, "查询讲座成功");
						List<Lecture> lectures = QueryLectureAnalysis
								.getData(response);
						if (null == lectures || 1 > lectures.size()) {
							queryCallBack.queryError(IQueryLectureCB.RESULR_NULL);
						} else {
							queryCallBack.querySuccess(lectures);
						}
					}
				} catch (JSONException e) {
					if (null != e.getMessage()) {
						LogcatUtils.e(TAG, e.getMessage());
					}
					queryCallBack.queryError(IQueryLectureCB.QUERY_ERROR);
				}

			}

			@Override
			public void onError(Exception e) {
				if (null != e.getMessage()) {
					LogcatUtils.e(TAG, e.getMessage());
				}
				queryCallBack.queryError(IQueryLectureCB.QUERY_ERROR);
			}
		});
	}

}
